<script setup>
import {
  Modal as AModal,
  Table as ATable,
  Button as AButton,
  Form as AForm,
  FormItem as AFormItem,
  Select as ASelect,
  DatePicker as ADatePicker,
  message
} from 'ant-design-vue'
import { ref, reactive, onMounted } from 'vue'
import SuspendEditModal from './SuspendEditModal.vue'
import {
  fetchPersonStatusList,
  fetchGroupList,
  fetchPersonList,
  savePersonStatusList
} from '@/api/claim'

/**
 * ant-design-vue将英文改为中文 DatePicker日期控件
 * https://blog.csdn.net/qq2754289818/article/details/130972771
 */
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
dayjs.locale('zh-cn')
const dateFormat = 'YYYY-MM-DD'
const rules = {
  startDate: [{ required: true, message: '请选择挂起开始日期', trigger: 'change' }]
}
const disabledDate = (current) => {
  // Can not select days before today and today
  return current && current < dayjs().startOf('day')
}
const props = defineProps({
  groupIdList: {
    type: Array,
    default: () => []
  }
})
const susPendVisible = defineModel()
const loading = ref(false)
let options = ref([])
let personOptions = ref([])

async function getGroupList() {
  let res = null
  try {
    res = await fetchGroupList()
  } catch (err) {
    console.log('err', err)
  }
  if (res?.success == '0') {
    options.value = res.data.list
  }
}
// 获取核赔人下拉列表
async function getPersonList() {
  let res = null
  try {
    const data = {
      groupNo: formState.groupNo
    }
    res = await fetchPersonList(data)
  } catch (err) {
    console.log('err', err)
  }
  if (res?.success == '0') {
    personOptions.value = res.data.list
  }
}
const handleChange = (value) => {
  console.log(`selected ${value}`, formState.groupNo)
  formState.person = []
  getPersonList()
}
function initData() {
  getGroupList()
  getPersonList()
  if (props.groupIdList.length > 0) {
    getTableList()
  }
}
onMounted(() => {
  initData()
})
function handleCancel() {
  susPendVisible.value = false
}
const formRef = ref()
const formState = reactive({
  groupNo: props.groupIdList,
  person: [],
  startDate: '',
  endDate: ''
})
function reset() {
  formState.groupNo = []
  formState.person = []
}
async function saveInfo() {
  formRef.value
    .validate()
    .then(async () => {
      let res = null
      const list = state.selectedRows.map(({ groupNo, operatorId, operatorName }) => {
        return {
          groupNo,
          operatorId,
          operatorName
        }
      })
      const daga = {
        startDate: formState.startDate,
        endDate: formState.endDate,
        list
      }
      try {
        res = await savePersonStatusList(daga)
      } catch (err) {
        console.log('err', err)
      }
      if (res?.success == '0') {
        getTableList()
        message.success('保存成功')
      }
    })
    .catch((error) => {
      console.log('error', error)
    })
}
// 获取tabledata
const columns = [
  {
    title: '序号',
    width: 70,
    dataIndex: 'Index',
    customRender: ({ text, record, index }) => `${index + 1}`
  },
  {
    title: '组名',
    dataIndex: 'groupName'
  },
  {
    title: '核赔人',
    dataIndex: 'operatorName'
  },
  {
    title: '工作状态',
    dataIndex: 'operatorStatus'
  },
  {
    title: '操作',
    key: 'operation',
    width: 100
  }
]
const pagination = reactive({
  current: 1,
  pageSize: 15,
  defaultPageSize: 15,
  pageSizeOptions: ['15', '30', '50', '100'],
  showSizeChanger: true,
  total: 0,
  onChange: handlePageChange,
  hideOnSinglePage: true
})
function handlePageChange(page, pageSize) {
  pagination.current = page
  pagination.pageSize = pageSize
  getTableList()
}
const state = reactive({
  selectedRowKeys: [], // Check here to configure the default column
  selectedRows: [], // Check here to configure the default column
  loading: false
})
const dataSource = ref([])
async function getTableList() {
  state.loading = true
  const data = {
    groupNo: formState.groupNo,
    operatorId: formState.person,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  let res = null
  try {
    res = await fetchPersonStatusList(data)
  } catch (err) {
    console.log('err', err)
  } finally {
    state.loading = false
  }
  if (res?.success == '0') {
    pagination.total = res.data.total
    dataSource.value = res.data.list
  }
}
function searchFun() {
  pagination.current = 1
  getTableList()
}
const onSelectChange = (selectedRowKeys, selectedRows) => {
  state.selectedRowKeys = selectedRowKeys
  state.selectedRows = selectedRows
}

// 挂起编辑
const modalVisible = ref(false)
let operatorId = ref('')
let operatorName = ref('')
let groupNo = ref('')
function operation(record) {
  modalVisible.value = true
  operatorId.value = record.operatorId
  operatorName.value = record.operatorName
  groupNo.value = record.groupNo
}
</script>
<template>
  <a-modal
    v-model:open="susPendVisible"
    :maskClosable="false"
    :keyboard="false"
    width="880px"
    title="挂起设置"
  >
    <template #footer>
      <div class="footer-modal">
        <a-button
          :disabled="state.selectedRowKeys.length <= 0"
          key="submit"
          type="primary"
          :loading="loading"
          @click="saveInfo"
          >保存</a-button
        >
        <a-button key="back" @click="handleCancel">关闭</a-button>
      </div>
    </template>
    <a-form
      :model="formState"
      labelAlign="left"
      ref="formRef"
      :rules="rules"
      layout="inline"
      autocomplete="off"
    >
      <a-form-item label="组名" name="groupNo">
        <a-select
          ref="select"
          mode="multiple"
          :showArrow="true"
          v-model:value="formState.groupNo"
          style="width: 220px"
          :field-names="{ label: 'groupName', value: 'groupNo' }"
          @change="handleChange"
          :options="options"
        ></a-select>
      </a-form-item>
      <a-form-item label="核赔人" name="person">
        <a-select
          ref="select"
          mode="multiple"
          :showArrow="true"
          v-model:value="formState.person"
          :field-names="{ label: 'operatorName', value: 'operatorId' }"
          style="width: 220px"
          :options="personOptions"
        ></a-select>
      </a-form-item>
      <a-form-item>
        <a-button class="search-btn" type="primary" @click="searchFun">查询</a-button>
        <a-button type="primary" @click="reset">重置</a-button>
      </a-form-item>
      <a-form-item>
        <p class="title">组内人员状态</p>
      </a-form-item>
      <a-table
        :scroll="{ x: 700, y: 400 }"
        size="small"
        class="ant-table-striped"
        bordered
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
        :data-source="dataSource"
        :row-key="(record) => record.operatorId"
        :pagination="pagination"
        :loading="state.loading"
        :row-selection="{
          selectedRowKeys: state.selectedRowKeys,
          onChange: onSelectChange
        }"
        :columns="columns"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'operation'">
            <span class="operation" @click="operation(record)">挂起编辑</span>
          </template>
        </template>
      </a-table>
      <a-form-item label="挂起开始日期" name="startDate">
        <a-date-picker
          :locale="locale"
          :disabled="state.selectedRowKeys.length <= 0"
          :format="dateFormat"
          :disabled-date="disabledDate"
          :valueFormat="dateFormat"
          v-model:value="formState.startDate"
        />
      </a-form-item>
      <a-form-item label="挂起结束日期" name="endDate">
        <a-date-picker
          :locale="locale"
          :disabled="state.selectedRowKeys.length <= 0"
          :format="dateFormat"
          :disabled-date="disabledDate"
          :valueFormat="dateFormat"
          v-model:value="formState.endDate"
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <SuspendEditModal
    v-if="modalVisible"
    :operator-id="operatorId"
    :group-no="groupNo"
    :operator-name="operatorName"
    @updateTable="getTableList"
    v-model="modalVisible"
  ></SuspendEditModal>
</template>
<style lang="scss" scoped>
.ant-btn-primary {
  background: #b6dff7;
  color: black;
}
.ant-table-striped {
  margin-bottom: 20px;
}
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}
.ant-table-striped :deep(.ant-table-thead) > tr > th {
  background-color: #fafafa;
}
.search-btn {
  margin-right: 20px;
}
.title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  margin-top: 20px;
}
.footer-modal {
  text-align: left;
  margin-top: 20px;
}
.operation {
  color: #459df8;
  cursor: pointer;
}
</style>
